import { useNavigate } from 'react-router-dom';
import { useEffect, useState} from 'react'
import '@/style/common/header.scss'
import pageEvent from "@/utils/pageEvent";
const zh_menu_list = [
	{
		index: 0,
		text: "首页",
		href: '/home',
	},
	{
		index: 1,
		text: "关于我们",
		href: '/intro',
	},
	{
		index: 2,
		text: "产品",
		href: '/industry',
	},
	{
		index: 3,
		text: "体系认证",
		href: '/systemCert',
	},
	{
		index: 4,
		text: "合作案例",
		href: '/cooperationCase',
	},
	{
		index: 5,
		text: "新闻中心",
		href: '/news',
	},
	{
		index: 6,
		text: "联系我们",
		href: '/contact',
	},
]

function Header() {
	const href = window.location.href
	const type = (href.indexOf('news/detail') !== -1 || href.indexOf('join') !== -1) ? 'white' : ''
	const [activeIndex, setActiveIndex] = useState(0);
	const [scrollTop, setScrollTop] = useState(0);
	const navigate = useNavigate();
	const jumpTo = (data) => {
		setActiveIndex(data.index);
		navigate(data.href);
	}
	useEffect(() => {
		setActiveMenu();
		if (type == "white") {
		  document.querySelector(".page-header").classList.add("white");
		}
	}, [])
	useEffect(() => {
		const scrollFn = pageEvent.scroll(onScroll)
		return () => {
		  pageEvent.destroy("scroll", scrollFn);
		}
	})
	useEffect(() => {
		if (type == "white") {
		  document.querySelector(".page-header").classList.add("white");
		} else {
		  document.querySelector(".page-header").classList.remove("white");
		}
	}, [type])
	const setActiveMenu = () => {
		const activeMenu = zh_menu_list.filter((item) => href.indexOf(item.href) !== -1) || []
		setActiveIndex(activeMenu.length ? activeMenu[0]?.index : 0);
	}
	const onScroll = (top, left) => {
		if (type == "white") {
			return
		}
		if (top > 90) {
			document.querySelector(".page-header").classList.add("white");
		} else {
			document.querySelector(".page-header").classList.remove("white");
		}
		document.querySelector(".page-header").style.left = -left + 'px';
		setScrollTop(top)
	}
	return (
		<>
			<nav className="page-header">
				<div className="mainContent">
					<div className="page-header-content">
						<a className="logo" href="/">
							<div className='logo-img'></div>
						</a>
						<ul
							id="header-com-nav-list"
							className="nav-list"
						>
							{zh_menu_list.map((menu, index) => {
								return (
									<li 
										className={["menu", activeIndex === index ? "active" : ''].join(" ")}
										key={index}
										onClick={jumpTo.bind(null, menu)}>
										<span className='m-text'>{menu.text}</span>
									</li>
								)
							})}
						</ul>
					</div>
				</div>
			</nav>
		</>
	)
}
export default Header